package com.google.project.client.ProjectManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.project.client.Service.DailyReportDetailService;
import com.google.project.client.Service.DailyReportDetailServiceAsync;
import com.google.project.client.Service.ProjTaskService;
import com.google.project.client.Service.ProjTaskServiceAsync;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.DailyReportDetailDTO;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.ProjectTaskDTO;

public class PMProjectTaskDetail extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField TextArea txtDescription;
	@UiField Label lblTaskName;
	@UiField Label lblParentName;
	@UiField Label lblStartDate;
	@UiField Label lblDuedate;
	@UiField Label lblWeight;
	@UiField Label lblSubcontructor;
	@UiField Label lblOperator;
	@UiField Label lblAmountOfWork;
	@UiField Label lblFinishedWork;
	@UiField Label lblProject;
	@UiField Button button;
	@UiField DateBox dbFromDate;
	@UiField DateBox dbToDate;
	@UiField  ListBox cboTypeStatistic;
	@UiField Button button_3;
	@UiField Button btnTaskReq;
	@UiField Label lblEndDate;

	interface Binder extends UiBinder<Widget, PMProjectTaskDetail> {
	}

	//_____________________________Common variable_____________________________

	private final ProjectServiceAsync projectService = GWT.create(ProjectService.class);
	private final ProjTaskServiceAsync projectTaskService = GWT.create(ProjTaskService.class);
	
	//private final DailyReportDetailServiceAsync dailyReportDetailService = GWT.create(DailyReportDetailService.class);
	
	private ProjectTaskDTO currTask  = new ProjectTaskDTO();
	private ProjectDTO currProject  = new ProjectDTO();
	
	//End__________________________Common variable_____________________________
	
	//________________________________Contructor_______________________________
	public PMProjectTaskDetail() {
		initWidget(binder.createAndBindUi(this));
		dbFromDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		dbToDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
	}
	
	public PMProjectTaskDetail(ProjectTaskDTO task) {
		currTask= task;
		initWidget(binder.createAndBindUi(this));
		if((currTask.getSubTasks()==null || currTask.getSubTasks().equals(""))&&currTask.getIsMile()==0){
			btnTaskReq.setVisible(true);
		}
		dbFromDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		dbToDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		displayData();
	}
	//End_____________________________Contructor_______________________________
	
	
	//_____________________________Common function_____________________________
	
	public void displayData()
	{
		cboTypeStatistic.addItem("khối lượng ngày","0");
		cboTypeStatistic.addItem("Tổng khối lượng","1");
		lblAmountOfWork.setText(currTask.getAmountOfWork() + " " +currTask.getUnit());
		lblTaskName.setText(currTask.getTaskName());
		Date dueDate = new Date(currTask.getDueDate()) ;
		lblDuedate.setText(CommonFuntion.convertToDate(dueDate));
		Date startDate = new Date(currTask.getStartDate()) ;
		lblStartDate.setText(CommonFuntion.convertToDate(startDate));
		Double com =CommonFuntion.fomatNumber(currTask.getFinishedWork()*100/currTask.getAmountOfWork());
		lblFinishedWork.setText(CommonFuntion.fomatNumber(currTask.getFinishedWork()) +" " + currTask.getUnit()+" ( "+com+"% )");
		if(!currTask.getOptAccountName().equals("0"))
		{
		lblOperator.setText(currTask.getOptAccountName());
		}
		lblWeight.setText(currTask.getWeight() + " %");
		if(currTask.getStatus()==2||currTask.getStatus()==3)
		{
			if(currTask.getFinishDate()!=null)
			{
				lblEndDate.setText(CommonFuntion.convertToDate(new Date(currTask.getFinishDate())));
			}
		}
		else
		{
			lblEndDate.setText("");
		}
		lblSubcontructor.setText(currTask.getSubContructor());
		if (currTask.getParentId() != 0) {
			
			projectTaskService.getTaskByTaskId(currTask.getParentId(),
					new AsyncCallback<ProjectTaskDTO>() {

						@Override
						public void onSuccess(ProjectTaskDTO result) {
							
							lblParentName.setText(result.getTaskName());
						}

						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub

						}
					});
		}
	
			
		projectService.getProjectById(currTask.getProjectId(), new AsyncCallback<ProjectDTO>() {
			
			@Override
			public void onSuccess(ProjectDTO result) {
				// TODO Auto-generated method stub
				lblProject.setText("Dự án : "+result.getProjectName());
				currProject = result;
			}
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	private native void drawLine(String datax,String realData,String planData,String unit,int isParent)
    /*-{
    if(isParent==1)
    {
    	 $wnd.drawLine(datax,realData,planData,"%");
    }else
    {
    	 $wnd.drawLine(datax,realData,planData,unit);
    }
   
    }-*/;
	
	@SuppressWarnings("deprecation")
	Long removeTime(Date date)
	{
		int houseTime =date.getHours()*60 * 60 * 1000;
		int minusTime =date.getMinutes()*60  * 1000;
	    int secTime = date.getSeconds()*1000;
	    Long time = (date.getTime()/1000);
	    Long mili = date.getTime() - 1000*time.intValue();
	   
	    Long newDate = date.getTime()-houseTime - minusTime-secTime-mili.intValue();
	   // Window.alert(date.getTime()+"  "+ newDate+"^_^" +mili);
	    
		return newDate;
	}
	@SuppressWarnings("deprecation")
	Long removeTime2(Date date)
	{
	String data = (date.getMonth()+1)+"/"+date.getDate()+"/"+(date.getYear()+1990);
	  Date newDate = new Date(data);
		return newDate.getTime();
	}
	Double getValueForDate(Long date,List<DailyReportDetailDTO> data)
	{
		for(DailyReportDetailDTO report:data)
		{
			Date reportDate= new Date( report.getCreatedOnDate());
			
			String compareDate =CommonFuntion.convertToDate( new Date(date)	);
			
			String  reportDateNoTime= CommonFuntion.convertToDate(reportDate);
			if(compareDate.equals(reportDateNoTime))
			{
				return report.getWorkToFinished();
			}
		}
		return 0d;
	}
	
Boolean checkTime()
{
    if(dbFromDate.getValue()==null)
    {
    	Window.alert("Từ ngày  không đúng định dạng ");
    	Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
	        public void execute () {
	        	dbFromDate.setFocus(true);
	        }
	    });
    	return false;
    }
    if(dbToDate.getValue()==null)
    {
    	Window.alert("Tới ngày không đúng định dạng ");
    	Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
	        public void execute () {
	        	dbToDate.setFocus(true);
	        }
	    });
    	return false;
    }
    
    if(CommonFuntion.removeTime(dbFromDate.getValue())>CommonFuntion.removeTime(dbToDate.getValue()))
    {
    	Window.alert("Từ ngày không thể lớn hơn tới ngày");
    	Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
	        public void execute () {
	        	dbToDate.setFocus(true);
	        }
	    });
    	return false;
    }
	return true;
	}
	@UiHandler("button")
	void onButtonClick(ClickEvent event) {
		
		if(checkTime())
		{
			 final List<Long> listUpdateTime = new ArrayList<Long>();
			 final List<Long> listUpdateTime2 = new ArrayList<Long>();
			 Date taskFromDate = new Date(currTask.getStartDate());
			 Date taskDueDate = new Date(currTask.getDueDate());
			 if(removeTime(dbFromDate.getValue())<removeTime(taskFromDate)||removeTime(dbToDate.getValue())>removeTime(taskDueDate))
			 {
				 Window.alert("Từ ngày -tới ngày không được nằm ngoài khoảng thời gian triển khai của công việc ");
			 }
			 else
			 {
			Date fromDate = new Date(removeTime(dbFromDate.getValue()));
			Date toDate = new Date(removeTime(dbToDate.getValue()));
			Date viewDate = toDate;
			Long dateDiff = (toDate.getTime() - fromDate.getTime()) / (24 * 60 * 60 * 1000);
			 if(dateDiff >30)
			 {
				 Window.alert("Thời gian thống kê không được vượt quá 30 ngày ");
			 }
			 else
			 {
				   for (int i = 0; i <= dateDiff.intValue(); i++) {
		               listUpdateTime.add(viewDate.getTime());
		               viewDate.setTime(viewDate.getTime() - 24 * 60 * 60 * 1000);
		           }
				   String dataX ="";
				   //lay dataX
				   for(int i =listUpdateTime.size()-1;i>=0;i--)
				   {
						Date dateData = new Date(listUpdateTime.get(i));
						if (dataX.equals("")) {

							dataX = dateData.getDate() + "-"
									+ (dateData.getMonth() + 1);
						} else {
							dataX += "," + dateData.getDate() + "-"
									+ (dateData.getMonth() + 1);
						}
					   listUpdateTime2.add(listUpdateTime.get(i));
				   }
				   final String dataX2=dataX;
				   projectTaskService.getDataForHightChart(currTask, listUpdateTime2, new AsyncCallback<List<Double>>() {
					
					@Override
					public void onSuccess(final List<Double> result) {
						// TODO Auto-generated method stub
						
						projectTaskService.getTatolWorkAtDate(currTask, listUpdateTime2.get(0), new AsyncCallback<Double>() {
							
							@Override
							public void onSuccess(Double workAtBegin) {
								// TODO Auto-generated method stub
								Double pre =0d;
								if(currTask.getGroup()!=0)
								{
									pre	=(workAtBegin/currTask.getAmountOfWork())*100;
									pre = CommonFuntion.fomatNumber(pre);
								}
								else
								{
									pre = workAtBegin;
									pre = CommonFuntion.fomatNumber(pre);
								}
							
								String realData ="";
								String planData="";
								//lay du lieu plan data
								Long planStart = removeTime(new Date(currTask.getStartDate()));
								Long planDue = removeTime(new Date(currTask.getDueDate()));
								Long dateDiff=(planDue-planStart)/(24*60*60*1000);
								Long datediffFromBegin= (removeTime(dbFromDate.getValue())-planStart)/(24*60*60*1000);;
							    Double planPerDay = currTask.getAmountOfWork()/(dateDiff+1);
								if(currTask.getGroup()==1)
								{
									planPerDay=100d/(dateDiff+1);
								}
								//int i =1;
								for(int i=0;i<listUpdateTime2.size();i++)
								{
									if (cboTypeStatistic.getValue(cboTypeStatistic.getSelectedIndex()).equals("0")) {
										if(result.size()==0)
										{
											if (realData.equals("")) {
												realData+=0.00;
											} else {
												realData+=","+0.00;
											}
										}
										else
										{
											if (realData.equals("")) {
												
												
												realData+=result.get(i);
											} else {
												realData+=","+result.get(i);
											}
										}
										
										//lay du lieu plan
										if (planData.equals("")) {
											planData += planPerDay;
										} else {
											planData += "," + planPerDay;
										}
									} else {
										if(result.size()==0)
										{
											if (realData.equals("")) {
												
												
												realData+=0.00;
											} else {
												realData+=","+0.00;
											}
										}else
										{
											if (realData.equals("")) {
												//pre += result.get(i);
												realData =""+pre;
											} else {
												Double check = result.get(i);
												pre += result.get(i);
												realData += ","+CommonFuntion.fomatNumber( pre);
											}
										}
										
										
										if (planData.equals("")) {
											planData += planPerDay*(datediffFromBegin + i+1);
										} else {
											planData += "," + planPerDay*(datediffFromBegin + i+1);
										}
									}
							
								}
								
								drawLine(dataX2,realData,planData,currTask.getUnit(),currTask.getGroup());
							}
							
							@Override
							public void onFailure(Throwable caught) {
								// TODO Auto-generated method stub
								
							}
						});
						
						
					}
					
					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						
					}
				});
				 } 
			 }
			
		}
	
	}

	@UiHandler("button_1")
	void onButton_1Click(ClickEvent event) {
		PMEntrypoint.get().PMProjectDetail(currProject.getProjectID());
	}
	@UiHandler("button_2")
	void onButton_2Click(ClickEvent event) {
		PMEntrypoint.get().PMProjectTaskStep2(currTask, currProject.getProjectID(),1);
	}
	//chuyen trang thai
	@UiHandler("btnStartTask")
	void onBtnStartTaskClick(ClickEvent event) {
//		if(currTask.getStatus()==3||currTask.getStatus()==2)
//		{
//			Window.alert("Bạn không thể thay đổi trạng thái của công việc đã hoàn thành hoặc ngừng thực hiện");
//		}
//		else
//		{
		PMChangeTaskStatus dialog = new PMChangeTaskStatus(currTask);
		dialog.setPopupPosition( 500, 250 );
		dialog.show();
//		}
	}
	@UiHandler("button_3")
	void onButton_3Click(ClickEvent event) {
		PMEntrypoint.get().ListDocuments(currTask.getId(), "2", currProject.getProjectName(), currTask.getTaskName());
	}
	@UiHandler("btnTaskReq")
	void onBtnTaskReqClick(ClickEvent event) {
		PMEntrypoint.get().PMProjectTaskStaff(currTask,currProject);
	}
}
